<script setup lang="js">
import {ref, onMounted, nextTick} from 'vue'
import VideoApi from "@/api/VideoApi.js";
import echarts from "@/utils/Echarts/echarts.js";
import dayjs from "dayjs";
import {useRouter} from "vue-router";
import User from "@/utils/User/User.js";
import { UserProfileApi } from '@/api/new/userProfleApi.js';
import { Document, VideoCamera, Goods, ArrowRight } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

const router = useRouter()

// 用户信息，改为从 API 获取
const userInfo = ref({
  username: '',
  userID: '',
  headshot: '',
  verified: true
});

// 用户统计数据，改为从 API 获取
const userStats = ref({
  following: 0,
  followers: 0,
  articles: 0
});

// 模拟用户进度
const userProgress = ref(userStats.value.articles/500);

// 统计数据，从API获取
const stats = ref({
  watchTime: 0,
  visitors: 0,
  likes: 0,
  favorites: 0,
  comments: 0,
  danmus: 0,
  newFollowers: 0,
  shares: 0,
  publishedArticles: 0,
  draftArticles: 0,
  totalComments: 0,
  secondHandItems: 0,
  disasters: 0,
  popularTags: []
});

// 成长榜样数据，使用固定的用户ID列表
const growthExampleUserIds = ref([
  '131', '103', '115', '107'
]);

// 成长榜样用户数据
const growthExamples = ref([]);

// 获取用户信息及统计数据
const fetchUserData = async () => {
  try {
    // 获取当前登录用户ID
    const userId = User.getUserId();
    if (!userId) {
      ElMessage.warning('请先登录');
      return;
    }

    // 获取用户基本信息
    const userData = await UserProfileApi.getUserInfo(userId);
    userInfo.value = {
      username: userData.username || '未知用户',
      userID: userData.userID || '',
      headshot: userData.headshot || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
      verified: true // 假设所有用户都是已认证的
    };

    // 获取用户统计数据
    try {
      // 获取关注数 - 使用 getFollowingCount API
      const followingResponse = await UserProfileApi.getFollowingCount(userId);

      const followingCount = followingResponse.followingCount || 0;

      // 获取粉丝数 - 使用 getFollowerCount API
      const followersResponse = await UserProfileApi.getFollowerCount(userId);
      const followersData = typeof followersResponse === 'string'
        ? JSON.parse(followersResponse)
        : followersResponse;
      const followersCount = followersData?.followCount || 0;

      // 获取文章数 - 使用 getPublishedArticleCount API
      const articlesResponse = await UserProfileApi.getPublishedArticleCount(userId);
      const articlesData = typeof articlesResponse === 'string'
        ? JSON.parse(articlesResponse)
        : articlesResponse;
      const articlesCount = articlesData?.publishedArticleCount || 0;

      userStats.value = {
        following: followingCount,
        followers: followersCount,
        articles: articlesCount
      };

      console.log('用户统计数据:', userStats.value);
    } catch (error) {
      console.error('获取用户统计数据失败:', error);
      userStats.value = {
        following: 0,
        followers: 0,
        articles: 0
      };
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
    ElMessage.error(`获取用户信息失败: ${error.message || '未知错误'}`);
  }
};

// 获取数据总览数据
const fetchStatsData = async () => {
  try {
    const userId = User.getUserId();
    if (!userId) {
      return;
    }

    // 1. 获取文章数据统计
    const articlesResponse = await UserProfileApi.viewPublishedArticles(userId);
    console.log('1. 获取文章数据统计', articlesResponse);
    if (articlesResponse) {

      // 收藏总数
      const totalFavorites = articlesResponse.reduce((sum, article) => {
        return sum + (article.favoriteCount || 0);
      }, 0);
      stats.value.favorites = totalFavorites;
      
      // 评论总数
      const totalComments = articlesResponse.reduce((sum, article) => {
        return sum + (article.commentCount || 0);
      }, 0);
      stats.value.comments = totalComments;

      const totalDrafts = articlesResponse.reduce((sum, article) => {
        return sum + (article.status === 'draft'? 1 : 0);
      }, 0);
      stats.value.draftArticles = totalDrafts;
      console.log('文章数据总览数据',stats.value)
    }

    // 2. 获取灾害数
    const disasterRes = await UserProfileApi.getDisasters(userId);
    stats.value.disasters = disasterRes.length;

    //3. 二手商品
    const sendhandRes =await UserProfileApi.getSecondHandItems(userId);
    stats.value.secondHandItems = sendhandRes.length;

  } catch (error) {
    console.error('获取统计数据失败:', error);
  }
};

// 获取成长榜样用户信息
const fetchGrowthExamples = async () => {
  try {
    const examplesList = [];
    
    // 获取每个用户的信息
    for (const userId of growthExampleUserIds.value) {
      try {
        const userData = await UserProfileApi.getUserInfo(userId);
        
        // 获取用户文章数
        const articlesResponse = await UserProfileApi.getPublishedArticleCount(userId);
        const articlesData = typeof articlesResponse === 'string'
          ? JSON.parse(articlesResponse)
          : articlesResponse;
        const articlesCount = articlesData?.publishedArticleCount || 0;
        
        // 获取用户粉丝数
        const followersResponse = await UserProfileApi.getFollowerCount(userId);
        const followersData = typeof followersResponse === 'string'
          ? JSON.parse(followersResponse)
          : followersResponse;
        const followersCount = followersData?.followCount || 0;
        
        examplesList.push({
          id: userId,
          username: userData.username || '未知用户',
          headshot: userData.headshot || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
          articles: articlesCount,
          followers: followersCount
        });
      } catch (error) {
        console.error(`获取用户 ${userId} 信息失败:`, error);
      }
    }
    
    growthExamples.value = examplesList;
  } catch (error) {
    console.error('获取成长榜样数据失败:', error);
  }
};

// 格式化进度条文本
const formatProgress = (percentage) => {
  return `${percentage}/500`;
};

// 查看所有权益
const viewAllPrivileges = () => {
  console.log('查看所有权益');
};

// 查看所有创作
const viewAllCreations = () => {
  router.push({name:'platform.article'});
};

// 创建图文笔记
const createTextNote = () => {
  router.push('/platform/upload/note');
};

// 创建灾害
const createVideoNote = () => {
  router.push('/platform/upload/disaster');
};

// 去开播
const goLive = () => {
  router.push('/platform/upload/secondhand');
};

// 查看详细统计
const viewDetailedStats = () => {
  router.push({ name: 'platform.dataBoard' });
};

// 查看更多成长榜样
const viewMoreExamples = () => {
  console.log('查看更多成长榜样');
};

// 查看用户详情
const viewUserDetail = (userId) => {
  router.push({
    path: '/otherUser',
    query: { userId }
  });
};

// 添加社区公约跳转方法
const navigateToCommunityRules = () => {
  router.push('/community-rules');
};

onMounted(() => {
  console.log('组件已挂载');
  fetchUserData(); // 加载用户数据
  fetchStatsData(); // 加载统计数据
  fetchGrowthExamples(); // 加载成长榜样数据
});
</script>

<template>
  <div class="platform-home">
    <div class="main-content">
      <!-- 用户信息卡片 -->
      <div class="user-profile-card">
        <div class="user-info-section">
          <div class="user-avatar">
            <el-avatar :size="64" :src="userInfo.headshot || '/default-avatar.png'"></el-avatar>
            <span class="verification-badge" v-if="userInfo.verified">
              <el-tooltip content="已认证用户" placement="top">
                <i class="el-icon-check"></i>
              </el-tooltip>
            </span>
          </div>
          <div class="user-details">
            <h2 class="username">{{ userInfo.username || '用户名' }}</h2>
            <div class="user-stats">
              <div class="stat-item">
                <span class="stat-value">{{ userStats.following }}</span>
                <span class="stat-label">关注</span>
              </div>
              <div class="stat-item">
                <span class="stat-value">{{ userStats.followers }}</span>
                <span class="stat-label">粉丝</span>
              </div>
              <div class="stat-item">
                <span class="stat-value">{{ userStats.articles }}</span>
                <span class="stat-label">文章</span>
              </div>
            </div>
            <div class="user-id">账号: {{ userInfo.userID }}</div>
          </div>
        </div>

        <div class="user-progress-section">
<!--          <div class="progress-header">-->
<!--            <span>成长积程起点，带着以下权益出发吧</span>-->
<!--            <el-button type="text" @click="viewAllPrivileges">查看全部 <i class="el-icon-arrow-right"></i></el-button>-->
<!--          </div>-->
          <div class="author-status">
            <span class="author-label">创作者任务</span>
            <el-tag size="small" type="success">游记进度中</el-tag>
          </div>
          <el-progress :percentage="userProgress" :format="formatProgress" :stroke-width="10" color="#FF2442"></el-progress>
<!--          <div class="progress-mascot">-->
<!--            <img src="https://img.yzcdn.cn/vant/cat.jpeg" alt="Mascot" class="mascot-image" />-->
<!--          </div>-->
        </div>
      </div>

      <!-- 创作中心 -->
      <div class="creation-center">
        <div class="section-header">
          <h3>新的创作</h3>
          <el-button type="text" @click="viewAllCreations">管理作品 <el-icon><ArrowRight /></el-icon></el-button>
        </div>

        <div class="creation-options">
          <div class="creation-option" @click="createTextNote">
            <div class="option-icon text-note">
              <el-icon><Document /></el-icon>
            </div>
            <div class="option-details">
              <h4>发布图文游记</h4>
              <p>支持图片格式: png, jpg, jpeg</p>
            </div>
          </div>

          <div class="creation-option" @click="createVideoNote">
            <div class="option-icon video-note">
              <el-icon><VideoCamera /></el-icon>
            </div>
            <div class="option-details">
              <h4>发布灾害信息</h4>
              <p>智能识别灾害类型</p>
            </div>
          </div>

          <div class="creation-option" @click="goLive">
            <div class="option-icon live-stream">
              <el-icon><Goods /></el-icon>
            </div>
            <div class="option-details">
              <h4>发布二手商品</h4>
              <p>二手商品流转</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 数据概览 -->
      <div class="data-overview">
        <div class="section-header">
          <div class="tabs">
            <span class="tab active">数据总览</span>
          </div>
          
        </div>

        <div class="stats-grid">
          <div class="stat-card">
            <div class="stat-title">已发布文章</div>
            <div class="stat-value">{{ stats.publishedArticles }}</div>
            <div class="stat-trend" :class="{ up: stats.publishedArticles > 0 }">
              {{ stats.publishedArticles > 0 ? '↑ 持续创作' : '开始创作' }}
            </div>
          </div>

          <div class="stat-card">
            <div class="stat-title">草稿箱</div>
            <div class="stat-value">{{ stats.draftArticles }}</div>
            <div class="stat-trend" :class="{ up: stats.draftArticles > 0 }">
              {{ stats.draftArticles > 0 ? '待完成' : '全部完成' }}
            </div>
          </div>

          <div class="stat-card">
            <div class="stat-title">总收藏数</div>
            <div class="stat-value">{{ stats.favorites }}</div>
            <div class="stat-trend" :class="{ up: stats.totalFavorites > 0 }">
              {{ stats.favorites > 0 ? '↑ 内容受欢迎' : '努力创作' }}
            </div>
          </div>

          <div class="stat-card">
            <div class="stat-title">总评论数</div>
            <div class="stat-value">{{ stats.comments }}</div>
            <div class="stat-trend" :class="{ up: stats.comments > 0 }">
              {{ stats.comments > 0 ? '↑ 友好互动' : '暂无互动' }}
            </div>
          </div>

          <div class="stat-card">
            <div class="stat-title">粉丝</div>
            <div class="stat-value">{{ userStats.followers }}</div>
            <div class="stat-trend" :class="{ up: stats.followers > 0 }">
              {{ stats.followers > 0 ? '↑ 有影响力' : '快快发布笔记吧' }}
            </div>
          </div>

          <div class="stat-card">
            <div class="stat-title">我的关注</div>
            <div class="stat-value">{{ userStats.following }}</div>
            <div class="stat-trend" :class="{ up: userStats.following > 0 }">
              {{ userStats.following > 0 ? '↑ 社区活跃' : '扩展好友吧！' }}
            </div>
          </div>

          <div class="stat-card">
            <div class="stat-title">二手商品</div>
            <div class="stat-value">{{ stats.secondHandItems }}</div>
            <div class="stat-trend" :class="{ up: stats.secondHandItems > 0 }">
              {{ stats.secondHandItems > 0 ? '↑ 在售中' : '暂无商品' }}
            </div>
          </div>

          <div class="stat-card">
            <div class="stat-title">灾害发布</div>
            <div class="stat-value">{{ stats.disasters }}</div>
            <div class="stat-trend" :class="{ up: stats.disasters > 0 }">
              {{ stats.disasters > 0 ? '↑ 安全贡献' : '暂无发布' }}
            </div>
          </div>
        </div>

        <!-- 热门标签展示 -->
        <div class="popular-tags-section" v-if="stats.popularTags.length > 0">
          <div class="section-header">
            <h3>我的热门标签</h3>
          </div>
          <div class="tags-container">
            <el-tag 
              v-for="(tag, index) in stats.popularTags" 
              :key="index"
              :type="['', 'success', 'warning', 'info', 'danger'][index % 5]"
              effect="light"
              size="medium"
              class="tag-item"
            >
              {{ tag.tag }} ({{ tag.count }})
            </el-tag>
            <div class="no-tags" v-if="stats.popularTags.length === 0">
              暂无标签数据
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧边栏 -->
    <div class="sidebar">
      <!-- 平台公告 -->
      <div class="platform-announcements">
        <h3>平台公告</h3>
        <div class="announcement-card" @click="navigateToCommunityRules">
          <div class="announcement-icon">
            <img src="https://img.yzcdn.cn/vant/cat.jpeg" alt="Community" />
          </div>
          <div class="announcement-content">
            <h4>社区公约</h4>
            <p>真诚分享，友好互动</p>
          </div>
        </div>
      </div>

      <!-- 成长榜样 -->
      <div class="growth-examples">
        <div class="section-header">
          <h3>成长榜样</h3>
          <el-button type="text" @click="viewMoreExamples">查看更多 <i class="el-icon-arrow-right"></i></el-button>
        </div>

        <div class="example-list">
          <div v-for="example in growthExamples" :key="example.id" class="example-item" @click="viewUserDetail(example.id)">
            <div class="example-image">
              <img :src="example.headshot" :alt="example.username" />
            </div>
            <div class="example-details">
              <h4>{{ example.username }}</h4>
              <p>文章数: {{ example.articles }}</p>
              <p>粉丝数: {{ example.followers }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="less">
.platform-home {
  margin-top: 20px;
  display: flex;
  gap: 20px;

  .main-content {
    flex: 3;
  }

  .sidebar {
    flex: 1;
  }

  .user-profile-card {
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    padding: 20px;
    margin-bottom: 20px;

    .user-info-section {
      display: flex;
      margin-bottom: 20px;

      .user-avatar {
        position: relative;
        margin-right: 20px;

        .verification-badge {
          position: absolute;
          bottom: 0;
          right: 0;
          background-color: #4CAF50;
          color: white;
          border-radius: 50%;
          width: 20px;
          height: 20px;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 12px;
        }
      }

      .user-details {
        flex: 1;

        .username {
          margin: 0 0 10px 0;
          font-size: 20px;
          font-weight: 600;
        }

        .user-stats {
          display: flex;
          margin-bottom: 10px;

          .stat-item {
            margin-right: 20px;
            display: flex;
            flex-direction: column;

            .stat-value {
              font-size: 18px;
              font-weight: 600;
              margin-bottom: 2px;
            }

            .stat-label {
              font-size: 12px;
              color: #999;
            }
          }
        }

        .user-id {
          font-size: 12px;
          color: #999;
        }
      }
    }

    .user-progress-section {
      position: relative;

      .progress-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;

        span {
          font-size: 14px;
          color: #333;
        }
      }

      .author-status {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;

        .author-label {
          font-size: 14px;
          font-weight: 500;
        }
      }

      .progress-mascot {
        position: absolute;
        right: 0;
        bottom: -10px;
        width: 60px;
        height: 60px;

        .mascot-image {
          width: 100%;
          height: 100%;
          object-fit: contain;
        }
      }
    }
  }

  .creation-center {
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    padding: 20px;
    margin-bottom: 20px;

    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      h3 {
        margin: 0;
        font-size: 18px;
        font-weight: 600;
      }
    }

    .creation-options {
      display: flex;
      gap: 15px;

      .creation-option {
        flex: 1;
        display: flex;
        align-items: center;
        padding: 15px;
        border-radius: 8px;
        background-color: #f5f5f5;
        cursor: pointer;
        transition: transform 0.3s ease, box-shadow 0.3s ease;

        &:hover {
          transform: translateY(-3px);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }

        .option-icon {
          width: 40px;
          height: 40px;
          border-radius: 8px;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 15px;
          font-size: 20px;

          &.text-note {
            background-color: #FFE0B2;
            color: #FF9800;
          }

          &.video-note {
            background-color: #BBDEFB;
            color: #2196F3;
          }

          &.live-stream {
            background-color: #FFCDD2;
            color: #F44336;
          }
        }

        .option-details {
          h4 {
            margin: 0 0 5px 0;
            font-size: 16px;
          }

          p {
            margin: 0;
            font-size: 12px;
            color: #999;
          }
        }
      }
    }
  }

  .data-overview {
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    padding: 20px;
    margin-bottom: 20px;

    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;

      .tabs {
        display: flex;
        gap: 15px;

        .tab {
          font-size: 16px;
          color: #999;
          cursor: pointer;
          padding-bottom: 5px;

          &.active {
            color: #333;
            font-weight: 500;
            border-bottom: 2px solid #FF2442;
          }
        }
      }
    }

    .stats-grid {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 15px;

      .stat-card {
        padding: 15px;
        border-radius: 8px;
        background-color: #f5f5f5;

        .stat-title {
          font-size: 14px;
          color: #666;
          margin-bottom: 5px;
        }

        .stat-value {
          font-size: 20px;
          font-weight: 600;
          margin-bottom: 5px;
        }

        .stat-trend {
          font-size: 12px;
          color: #999;

          &.up {
            color: #4CAF50;
          }

          &.down {
            color: #F44336;
          }
        }
      }
    }
  }

  .sidebar {
    .platform-announcements, .growth-examples {
      background-color: white;
      border-radius: 8px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
      padding: 20px;
      margin-bottom: 20px;

      h3 {
        margin: 0 0 15px 0;
        font-size: 18px;
        font-weight: 600;
      }
    }

    .announcement-card {
      display: flex;
      align-items: center;
      padding: 15px;
      background-color: #FFF5F5;
      border-radius: 8px;

      .announcement-icon {
        width: 40px;
        height: 40px;
        margin-right: 15px;

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
          border-radius: 8px;
        }
      }

      .announcement-content {
        h4 {
          margin: 0 0 5px 0;
          font-size: 16px;
          color: #FF2442;
        }

        p {
          margin: 0;
          font-size: 12px;
          color: #666;
        }
      }
    }

    .growth-examples {
      .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;

        h3 {
          margin: 0;
        }
      }

      .example-list {
        display: flex;
        flex-direction: column;
        gap: 15px;

        .example-item {
          display: flex;
          align-items: center;
          cursor: pointer;

          &:hover {
            .example-details h4 {
              color: #FF2442;
            }
          }

          .example-image {
            width: 60px;
            height: 60px;
            border-radius: 8px;
            overflow: hidden;
            margin-right: 15px;

            img {
              width: 100%;
              height: 100%;
              object-fit: cover;
            }
          }

          .example-details {
            h4 {
              margin: 0 0 5px 0;
              font-size: 14px;
              transition: color 0.3s ease;
            }

            p {
              margin: 0;
              font-size: 12px;
              color: #999;
            }
          }
        }
      }
    }
  }
}

// 响应式调整
@media (max-width: 1200px) {
  .platform-home {
    flex-direction: column;

    .main-content, .sidebar {
      width: 100%;
    }
  }
}

.popular-tags-section {
  margin-top: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}

.tag-item {
  margin-right: 8px;
  margin-bottom: 8px;
  font-size: 14px;
}

.no-tags {
  color: #909399;
  font-size: 14px;
  padding: 10px 0;
}
</style>
